package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/ddlin/kit/xlog"
	"gitee.com/ddlin/tiktok-go-tool/inject"
	"gitee.com/ddlin/tiktok-go-tool/internal/middleware"
)

func main() {
	app, cleanup, err := inject.InitApp()
	if err != nil {
		panic(err.Error())
	}
	middleware.InitMiddleware(app.Engine)
	defer cleanup()

	ctx := app.Ctx

	xlog.S(ctx).Info("service start")
	srv := &http.Server{
		Addr:    app.Config.Bind,
		Handler: app.Engine,
	}

	app.Router.Register()

	//Http server  Run
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			xlog.S(ctx).Fatalw("listen err", "err", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
	<-quit
	xlog.S(ctx).Info("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		xlog.S(ctx).Fatalw("Server Shutdown err", "err", err)
	}
	xlog.S(ctx).Info("Server exiting")
}
